<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\facade\Cache;
use think\facade\Config;
use think\facade\Request;


function show_cid_name ($cid = 0){
    $site_config = Config::pull("site_config");
    if (empty($site_config)) {
        return "暂无分类";
    }

    $category_array = array();
    if (is_array($site_config['categorys'])) {
        foreach ($site_config['categorys'] as $category) {
            $category_array[$category['id']] = array(
                'name' => $category['name'],
                'alias' => $category['alias']
            );
        }
    }
    if (array_key_exists($cid,$category_array)) {
        return $category_array[$cid]['name'];
    }
    return "暂无分类";
}

/**
 * 请求远程地址
 * @param string $url 地址
 * @param string $cookie
 * @return array
 */
function curl_url($url = '', $param = array(), $cookie = '')
{
    $header[] = "Content-type: application/x-www-form-urlencoded";
    $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 2);

    if (!empty($cookie)) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    if (!empty($param) && is_array($param)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
    }

    $html = curl_exec($ch);
    curl_close($ch);
    return json_decode($html,true);
}

/**
 * 熊掌号时间格式化
 * @param string $time 时间戳
 * @return string\
 */
function t_date($time = '') {
    return date("Y-m-d",$time) . "T" . date("H:i:s",$time);
}


/**
 * 下载图片
 * @param string $url
 * @return string
 */
function down_image($url = '') {

    $server_config = Config::pull("server");
    if (strpos($url,"http") === false){
        $url = $server_config['server_url'] . "/" . $url;
    }

    $dir = pathinfo($url);

    if (array_key_exists("extension",$dir)) {
        $fileName = "images/" . md5($url) .".". $dir['extension'];
    } else {
        $fileName = "images/" . md5($url);
    }

    if (file_exists($fileName)) {
        return "/" . $fileName;
    }else {
        $data = curl_down_file($url);
        if (empty($data))
        {
            return $url;
        }

        //本地文件返回
        if (book_write_file($fileName,$data)){
            return "/" . $fileName;
        }
    }

    return $url;
}



/**
 * 下载文件
 * @param string $url
 * @return mixed
 */
function curl_down_file($url = '') {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    $data = curl_exec($ch);
    curl_close($ch);
    if (empty($data)) {
        $data = file_get_contents($url);
    }
    return $data;
}
function book_arr2file($f, $arr = '')
{
    if (is_array($arr)) {
        $con = var_export($arr, true);
    } else {
        $con = $arr;
    }
    $con = "<?php\nreturn $con;\n?>";
    return book_write_file($f, $con);
}

function book_read_file($f)
{
    return @file_get_contents($f);
}

function book_write_file($fileName, $content = '')
{
    $dir = dirname($fileName);
    if (!is_dir($dir)) {
        book_mkdirss($dir);
    }
    return @file_put_contents($fileName, $content);
}

function book_mkdirss($path, $mode = 0777)
{
    if (!is_dir(dirname($path))) {
        book_mkdirss(dirname($path));
    }
    if (!file_exists($path)) {
        return mkdir($path, $mode);
    }
    return true;
}

/**
 * 生成随机数
 * @param int $length
 * @return string
 */
function make_rand($length = 8, $chars = null)
{
    if (is_null($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

/**
 * 数组key转大小写
 * @param $array
 * @param int $case
 */
function array_case(&$array, $case = CASE_LOWER)
{
    $array = array_change_key_case($array, $case);
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            array_case($array[$key], $case);
        }
    }
}

/**
 * 字符串截取
 * @param $str
 * @param int $start
 * @param $length
 * @param string $charset
 * @param bool $suffix
 * @return bool|string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr")) {
        if ($suffix)
            return mb_substr($str, $start, $length, $charset) . "...";
        else
            return mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        if ($suffix)
            return iconv_substr($str, $start, $length, $charset) . "...";
        else
            return iconv_substr($str, $start, $length, $charset);
    }
    $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    if ($suffix) return $slice . "…";
    return $slice;
}

/**
 * 内容替换函数 本函数取自 ygbook
 * @param string $replace 替换规则 {filter replace='替换后内容'}<div class="ad">(.*)</div>{/filter}
 * @param string $content 待替换的内容
 * @return mixed|null|string|string[]
 */
function filter_content($replace = '', $content = '')
{
    $filterArray = explode("\n", $replace);
    foreach ($filterArray as $item) {
        preg_match("#^\\{filter\\s+replace\\s*=\\s*'([^']*)'\\s*\\}(.*)\\{/filter\\}#", $item, $matches);
        if (isset($matches[2]) && !empty($matches[2])) {
            $matches[2] = str_replace('~', '\\~', $matches[2]);
            $matches[2] = str_replace('"', '\\"', $matches[2]);
            $content = @preg_replace('~' . $matches[2] . '~iUs', $matches[1], $content);
        } else {
            $content = str_replace($item, '', $content);
        }
    }
    return trim($content);
}


function curl_server($url = "") {
    $key = md5($url);

    $app_debug = Config::get("app_debug");
    if (Cache::has($key) && $app_debug == false) {
        return Cache::get($key);
    }else {
        $server_config = Config::pull("server");
        $data = curl_url(sprintf("%s/%s",trim( $server_config['server_url']),$url), array("appkey" => trim($server_config['app_key'])));
        if ($data['code'] == 0) {
            $result = array('data' => $data["data"],'cache' => $data["cache"]);
            Cache::set($key,$result,3600);
            return $result;
        }else {
            throw new \think\Exception($data['msg']);
        }
    }
}


/**
 * 判断是否移动端域名
 * @param string $prefix
 * @return bool
 */
function isMobileDomain($prefix = 'm')
{
    $domain = str_replace(array('https://','http://'),'',strtolower(Request::domain()));
    $domain = explode('.',$domain);
    if (is_array($domain) && $domain[0] == $prefix) {
        return true;
    }
    return false;
}